<style lang="less" scoped>
@import "../assets/css/config.less";
*{
  margin: 0;
  padding: 0;
}
.xuanxiang{
  display: flex;
  flex-direction: column;
  justify-content: start;
}

.xuanxiang span{
  font-size: 14px;
}
.index {
  background: #f8f8f9;
}
.flex-column{
  display: flex;
  flex-direction: column;
}
.loading {
  animation: myloading 1s linear infinite;
  margin-top: 100px;
}
@keyframes myloading {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.out {
  position: relative;
  display: flex;
  justify-content: center;
}
.ques_content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}
.ques_content p:first-of-type {
  font-weight: bold;
}

.check {
  position: absolute;
  margin-top: 10px;
  left: 50%;
}
.collection {
  position: relative;
  margin: 20px 0;
}
.right_no {
  margin-right: -180px;
}
.el-icon-star-on {
  color: #ffaf03;
}
.el-icon-star-off {
  color: #c9ccc3;
}
.answer {
  position: absolute;
  left: 0;
  top: 50px;
}

.column-one {
  width: 16px;
  height: 100px;
}
.backBeforeOne {
  position: fixed;
  top: 175px;
}
.backPoint {
  position: fixed;
  top: 128px;
}
.correctRate-title {
  margin-top: 15px;
  font-weight: 600;
  font-size: 14px;
  float: left;
}
.correctRate {
  font-size: 14px;
  color: @color2;
}
.editor {
  width: 70%;
}
.header{
  position: fixed;
  top:0;
  width: 100%;
  min-width: 1210px;
  z-index: 999;
}
.center-area{
  margin: 20px;
}
.button{
  background-color: @color1;
  color: @white;
  border: none;
  outline: none;
  border-radius: 4px;
  padding: 0px 15px;
  font-size: 13px;
  line-height: 32px;
  &:hover {
    background-color:@color2;
  }
  &:active {
    background-color:@color3;
  }
}
a{
  color: @color2;
  font-size: 14px;
}
a:active{
  color: @color3;
}
</style>

<template>
  <div id="index">
    <div class="header">
      <myheader></myheader>
    </div>
    <Layout style="margin-top: 60px" id="content">

      <Layout :style="{padding: '0 24px 24px','background-color': 'white','min-width': '1210px'}">
        <div style="padding: 15px 6px">
          <my-breadcrumb :prop="breadcrumbList"></my-breadcrumb>
        </div>
        <div class="out" id="out">
          <div class="collection">
            <span
              style="background-color:white;font-size:30px;"
              :class="collection?'el-icon-star-on':'el-icon-star-off'"
              @click="collect"
            ></span>
            <a class="answer" @click.prevent="allAnswer" >提问</a>
          </div>
          <div class="center-area">
            <Card style="width:900px;margin-bottom: 20px;text-align:left;">
              <div class="ques_content">
                <p v-if="point.bloom === 1">(布鲁姆认知层次：记忆)</p>
                <p v-if="point.bloom === 2">(布鲁姆认知层次：理解)</p>
                <p v-if="point.bloom === 3">(布鲁姆认知层次：应用)</p>
                <p v-if="point.bloom === 4">(布鲁姆认知层次：分析)</p>
                <p v-if="point.bloom === 5">(布鲁姆认知层次：综合)</p>
                <p v-if="point.bloom === 6">(布鲁姆认知层次：评价和创造)</p>
                <div v-html="point.practice.question_editor_Content"></div>

                <RadioGroup
                  class="xuanxiang"
                  v-if="point.practice.type === 'panduan'"
                  v-model="radio_value"
                  :key="toString(Math.random())"
                >
                  <Radio label="yes">
                    <span>正确</span>
                  </Radio>
                  <Radio label="no">
                    <span>错误</span>
                  </Radio>
                </RadioGroup>

                <CheckboxGroup
                  class="xuanxiang"
                  v-if="point.practice.type === 'xuanze'"
                  v-model="checkbox_value"
                  :key="toString(Math.random())"
                >
                  <Checkbox
                    v-for="(item, index) in point.practice.items"
                    :label="index + 1 + ''"
                    :key="index"
                  >
                    <span v-if="index === 0">A</span>
                    <span v-if="index === 1">B</span>
                    <span v-if="index === 2">C</span>
                    <span v-if="index === 3">D</span>
                    <span v-if="index === 4">E</span>
                    <span v-if="index === 5">F</span>
                    <span v-if="index === 6">G</span>
                    <span v-if="index === 7">H</span>
                    <span v-if="index === 8">I</span>
                    <span v-if="index === 9">J</span>
                    <span>{{item}}</span>
                  </Checkbox>
                </CheckboxGroup>
                <div v-show="point.practice.type === 'jianda'" style="margin: 15px 0 0;width: 100%">
                  <div ref="editor" style="text-align:left;width: 100%"></div>
                </div>
              </div>
            </Card>

            <button class="button" @click="submit" style="display:inline;width: 160px;" :disabled="!see">提交并查看解析</button>
            <div class="check" v-if="show && point.practice.type !=='jianda'">
              <el-button
                type="success"
                icon="el-icon-check"
                circle
                size="mini"
                v-if="correct"
                class="right_no"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-close"
                circle
                size="mini"
                v-if="error"
                class="right_no"
              ></el-button>
            </div>
            <el-collapse-transition>
              <div v-if="show" class="flex-column">
                <div class="correctRate-title">
                  <span>本题全网正确率：</span>
                  <span class="correctRate">{{ correctRate }}%</span>
                </div>
                <Card style="width:900px;margin: 20px auto 20px auto;text-align: left">
                  <div>
                    答案：
                    <div v-if="point.practice.type === 'jianda'">言之有理即可</div>
                    <div v-if="point.practice.type === 'panduan'">
                      <p v-if="point.practice.answer === 'yes'">正确</p>
                      <p v-if="point.practice.answer === 'no'">错误</p>
                    </div>
                    <div v-if="point.practice.type === 'xuanze'">
                      <div v-for="(item, index) in point.practice.answer" :key="index">
                        <p v-if="item === '1'">A</p>
                        <p v-if="item === '2'">B</p>
                        <p v-if="item === '3'">C</p>
                        <p v-if="item === '4'">D</p>
                        <p v-if="item === '5'">E</p>
                        <p v-if="item === '6'">F</p>
                        <p v-if="item === '7'">G</p>
                        <p v-if="item === '8'">H</p>
                        <p v-if="item === '9'">I</p>
                        <p v-if="item === '10'">J</p>
                      </div>
                    </div>
                  </div>
                  <div v-if="point.practice.illustrationContent!==''">
                    答案解析：
                    <div v-html="point.practice.illustrationContent"></div>
                  </div>
                </Card>
              </div>
            </el-collapse-transition>
            <div v-if="show">
              <el-popover placement="right-end" width="270" trigger="hover" content="题库耗尽时会出现重复的题目哦～">
                <button slot="reference" class="button"  style="width: 160px;" @click="nextproblem">再来一题</button>
              </el-popover>
            </div>
          </div>
          
          <div class="flex-column" style="margin: 20px 0">
            <button
              class="button"
              style="margin-bottom:20px"
              @click="backPoint"
            >返回知识点</button>
            <button
              @click="backBeforeOne"
              v-if="problem_num>0"
              class="button"
            >返回上一题</button>
          </div>
        </div>
      </Layout>
    </Layout>
  </div>
</template>

<script>
import header from "../components/header.vue";
import connectUs from "../components/connectUs.vue";
import myBreadcrumb from "../components/myBreadcrumb.vue";
import E from "wangeditor";
import {
  add_record,
  next_problem,
  collect_pro,
  getCollectedQuestionIs,
  getSingleRecord
} from "../api/api";

export default {
  name: "edit_point",
  data: function() {
    return {
      bg: {
        width: `${window.innerWidth}px`,
        height: "auto",
        overflow: "scroll"
      },
      connectTop: {
        right: `${window.innerWidth * 0.02}px`,
        top: ""
      },
      pointLeft: {
        left: ""
      },
      editorContent: "",
      user: {},
      point: {},
      radio_value: "",
      checkbox_value: [],
      attachment: true,
      question_ID: "",
      show: false,
      error: false,
      correct: false,
      collection: false,
      flag: 0,
      userGroup: "",
      currentPoint: {},
      showComt: false,
      question_list: [],
      problem_num: 0,
      see: true,
      correctRate: -1
    };
  },
  created() {
    if (JSON.parse(sessionStorage.getItem("currentQuestion")) != null) {
      this.currentPoint = JSON.parse(sessionStorage.getItem("currentQuestion"));
    } else {
      this.currentPoint = JSON.parse(sessionStorage.getItem("currentPoint"));
    }
    this.point = this.currentPoint.point;
    if (JSON.parse(sessionStorage.getItem("questionList")) != null) {
      this.question_list = JSON.parse(sessionStorage.getItem("questionList"));
    }
    // 获取面包屑数组
    if (JSON.parse(sessionStorage.getItem("pathList")) != null) {
      let breadcrumbList = JSON.parse(sessionStorage.getItem("pathList"));
      this.breadcrumbList = [...breadcrumbList, {name: '做题'}]
    }
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        let content_top = document.getElementById("content").offsetTop;
        this.bg.height = `${window.innerHeight - content_top}px`;
        this.bg.width = `${window.innerWidth}px`;
        let that = this;
        setTimeout(function() {
          that.pointLeft.left = `${document.getElementById("out").offsetWidth *
            0.5 +
            375}px`;
        }, 10);
      })();
    };
    let content_top = document.getElementById("content").offsetTop;
    this.pointLeft.left = `${document.getElementById("out").offsetWidth * 0.5 +
      375}px`;
    this.bg.height = `${window.innerHeight - content_top}px`;
    this.connectTop.top = `${window.innerHeight * 0.8}px`;
    this.user = JSON.parse(this.$store.state.user);
    let user = JSON.parse(this.$store.state.user);
    this.userGroup = this.user.userGroup;

    let point = this.currentPoint.point;
    this.flag = this.currentPoint.flag;
    
    if (this.point.practice.type === "jianda") {
      var editor = new E(this.$refs.editor);
      editor.customConfig.onchange = html => {
        this.editorContent = html;
      };
      var url = "";
      if (process.env.NODE_ENV === "development") {
        url = "http://localhost:8080/api/uploadImg";
      } else if (process.env.NODE_ENV === "production") {
        url = "https://www.ourspark.org/api/uploadImg";
      }
      editor.customConfig.uploadImgServer = url;
      editor.customConfig.zIndex = 0;
      editor.create();
      editor.txt.html("<p>请在此输入你的答案</p>");
    }
    this.showProblem(point);
  },
  components: {
    myheader: header,
    connectUsVue: connectUs,
    'my-breadcrumb': myBreadcrumb
  },
  methods: {
    allAnswer(index) {
      this.$router.push({
        name: "allanswer",
        params: {
          menu: this.currentPoint.point.menu,
          point_id: this.currentPoint.point._id,
          point_title: this.currentPoint.point.title,
          point: this.point
        }
      });
    },
    backPoint() {
      this.$router.go(-1);
    },
    backBeforeOne() {
      this.problem_num--;
      this.see = false;
      this.show = true;
      sessionStorage.setItem(
        "questionList",
        JSON.stringify(this.question_list)
      );
      this.point = JSON.parse(this.question_list[0]).point;
      if (JSON.parse(this.question_list[0]).point.practice.type === "xuanze") {
        this.checkbox_value = JSON.parse(this.question_list[0]).choose_checkbox;
      } else if (
        JSON.parse(this.question_list[0]).point.practice.type === "jianda"
      ) {
        var editor = new E(this.$refs.editor);
        editor.customConfig.onchange = html => {
          this.editorContent = html;
        };
        var url = "";
        if (process.env.NODE_ENV === "development") {
          url = "http://localhost:8080/api/uploadImg";
        } else if (process.env.NODE_ENV === "production") {
          url = "https://www.ourspark.org/api/uploadImg";
        }
        editor.customConfig.uploadImgServer = url;
        editor.customConfig.zIndex = 0;
        editor.create();
        editor.txt.html(JSON.parse(this.question_list[0]).choose_editor);
        this.editorContent = JSON.parse(this.question_list[0]).choose_editor;
      } else {
        this.radio_value = JSON.parse(this.question_list[0]).choose_radio;
      }
      if (JSON.parse(this.question_list[0]).result) {
        this.correct = true;
        this.error = false;
      } else {
        this.correct = false;
        this.error = true;
      }
      //判断是否是知识点附带的基本题
      if (this.question_list.length === 1) {
        this.attachment = true;
      }
      this.question_list.splice(0, 1);
      let question_ID = "";
      if (this.question_list.length !== 0) {
        question_ID = this.point.question_ID;
      }
      getSingleRecord({
        flags: this.user.flags,
        question_ID: question_ID,
        point_ID: this.point._id
      })
        .then(response => {
          if (response.state === true) {
            this.correctRate = parseFloat(response.right_rate.toFixed(2));
          } else {
            this.$Message.error(response.msg);
          }
        })
        .catch(error => {
          this.$Message.error(error.status);
        });
    },
    nextproblem() {
      this.see = true;
      //返回上一题列表
      this.question_list.unshift(
        JSON.stringify({
          point: this.point,
          choose_checkbox: this.checkbox_value,
          choose_radio: this.radio_value,
          choose_editor: this.editorContent,
          result: this.correct
        })
      );
      sessionStorage.setItem(
        "questionList",
        JSON.stringify(this.question_list)
      );

      this.problem_num++;
      this.correct = false;
      this.error = false;
      this.show = false;
      this.radio_value = "";
      this.checkbox_value = [];
      this.editorContent = "";

      let that = this;
      let point = this.currentPoint.point;
      next_problem({
        position: point.menu,
        point_id: point._id
      })
        .then(response => {
          if (response.state === true) {
            let that = this;
            point = response.result;
            this.point.practice.answer = point.answer;
            if (point.type === "panduan")
              this.point.practice.answer = this.point.practice.answer.join("");
            this.point.practice.illustrationContent = point.illustrationContent;
            this.point.practice.items = point.items;
            this.point.practice.question_editor_Content = point.question;
            this.point.practice.type = point.type;
            this.point._id = point.point_id;
            this.point.question_ID = point._id;
            this.point.bloom = point.bloom;
            this.attachment = false;
            if (this.point.practice.type === "jianda") {
              var editor = new E(that.$refs.editor);
              editor.customConfig.onchange = html => {
                that.editorContent = html;
              };
              var url = "";
              if (process.env.NODE_ENV === "development") {
                url = "http://localhost:8080/api/uploadImg";
              } else if (process.env.NODE_ENV === "production") {
                url = "https://www.ourspark.org/api/uploadImg";
              }
              editor.customConfig.uploadImgServer = url;
              editor.customConfig.zIndex = 0;
              editor.create();
              editor.txt.html("<p>请在此输入你的答案</p>");
            }

            //                          that.showProblem(point);
            //把当前题目信息存入缓存
            sessionStorage.setItem(
              "currentQuestion",
              JSON.stringify({
                flag: this.currentPoint.flag,
                last: this.currentPoint.last,
                point: {
                  bloom: this.point.bloom,
                  content: this.point.content,
                  menu: this.point.menu,
                  practice: this.point.practice,
                  seq: this.point.seq,
                  title: this.point.title,
                  __v: this.point.__v,
                  _id: this.point.question_ID
                }
              })
            );
          } else {
            that.$Message.error(response.msg);
          }
          return getCollectedQuestionIs({
            UUID: this.user.UUID,
            question_ID: this.point.question_ID
          });
        })
        .then(response => {
          if (response.state === true) {
            this.collection = response.isCollectioned;
          } else {
            this.$Message.error(response.msg);
          }
        })
        .catch(error => {
          that.$Message.error(error.status);
        });
    },
    showProblem(point) {
      let user = JSON.parse(this.$store.state.user);
      let course = point.menu.split(",")[0];
      if (course === "js") {
        if (
          user.process[0].length === 0 ||
          user.process[1] < parseInt(course[1]) ||
          (user.process[1] === parseInt(course[1]) &&
            user.process[2] < parseInt(course[2]))
        ) {
          this.point = point;
          this.attachment = true;
        } else {
        }
      } else if (course === "wx") {
        this.point = point;
        if (
          user.process[1].length === 0 ||
          user.process[1] < parseInt(course[1]) ||
          (user.process[1] === parseInt(course[1]) &&
            user.process[2] < parseInt(course[2]))
        ) {
          this.point = point;
          this.attachment = true;
        } else {
        }
      } else if (course === "ydhlw") {
        this.point = point;
        if (
          user.process[2].length === 0 ||
          user.process[1] < parseInt(course[1]) ||
          (user.process[1] === parseInt(course[1]) &&
            user.process[2] < parseInt(course[2]))
        ) {
          this.point = point;
          this.attachment = true;
        } else {
        }
      }
      getCollectedQuestionIs({
        UUID: this.user.UUID,
        question_ID: this.point._id
      })
        .then(response => {
          if (response.state === true) {
            this.collection = response.isCollectioned;
          } else {
            this.$Message.error(response.msg);
          }
        })
        .catch(error => {
          this.$Message.error(error.status);
        });
    },
    collect() {
      let json = null;
      if (this.collection) {
        this.collection = false;
        if (this.attachment) {
          json = {
            attachment: this.attachment,
            question_ID: this.point._id,
            UUID: this.user.UUID,
            cancel: true
          };
        } else {
          json = {
            attachment: this.attachment,
            question_ID: this.point.question_ID,
            UUID: this.user.UUID,
            cancel: true
          };
        }
        collect_pro(json)
          .then(response => {
            if (response.state === true) {
              // this.show = true;
              this.$Message.success('取消收藏成功');
            } else {
              this.$Message.error(response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      } else {
        this.collection = true;
        if (this.attachment) {
          json = {
            attachment: this.attachment,
            question_ID: this.point._id,
            UUID: this.user.UUID,
            cancel: false
          };
        } else {
          json = {
            attachment: this.attachment,
            question_ID: this.point.question_ID,
            UUID: this.user.UUID,
            cancel: false
          };
        }
        collect_pro(json)
          .then(response => {
            if (response.state === true) {
              //                        this.show = true;
              this.$Message.success('收藏成功');
            } else {
              this.$Message.error(response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      }
    },
    submit() {
      let stu_answer = [];
      let result = false;
      if (this.point.practice.type === "panduan") {
        if (this.radio_value !== "") {
          stu_answer.push(this.radio_value);
          if (
            this.radio_value === this.point.practice.answer ||
            this.radio_value === this.point.practice.answer[0]
          ) {
            result = true;
            this.correct = true;
            this.error = false;
          } else {
            this.correct = false;
            this.error = true;
          }
        }
      } else if (this.point.practice.type === "xuanze") {
        if (this.checkbox_value.length > 0) {
          stu_answer = this.checkbox_value;

          if (
            this.checkbox_value.sort().toString() ===
            this.point.practice.answer.sort().toString()
          ) {
            result = true;
            this.correct = true;
            this.error = false;
          } else {
            this.correct = false;
            this.error = true;
          }
        }
      } else {
        if (this.editorContent !== "") {
          stu_answer.push(this.editorContent);
          result = true;
          this.correct = true;
          this.error = false;
        }
      }
      let json = null;
      if (this.attachment) {
        json = {
          lastOrNot: this.currentPoint.last,
          menu: this.point.menu,
          seq: this.point.seq,
          point_ID: this.point._id,
          attachment: this.attachment,
          question_ID: "",
          UUID: this.user.UUID,
          stu_answer: stu_answer,
          result: result,
          updateProcess: this.flag,
          time: +new Date()
        };
      } else {
        json = {
          lastOrNot: this.currentPoint.last,
          menu: this.point.menu,
          seq: this.point.seq,
          point_ID: this.point._id,
          attachment: this.attachment,
          question_ID: this.point.question_ID,
          UUID: this.user.UUID,
          stu_answer: stu_answer,
          result: result,
          updateProcess: this.flag,
          time: +new Date()
        };
      }
      if (stu_answer.length === 0) {
        this.$Modal.confirm({
          title: "提示",
          content: "您还没做题！"
        });
      } else {
        //question_ID
        add_record(json)
          .then(response => {
            if (response.state === true) {
              this.show = true;
            } else {
              this.$Message.error(response.msg);
            }
            //获取正确率
            let question_ID = "";
            if (this.question_list.length !== 0) {
              question_ID = this.point.question_ID;
            }
            return getSingleRecord({
              flags: this.user.flags,
              question_ID: question_ID,
              point_ID: this.point._id
            });
          })
          .then(response => {
            if (response.state === true) {
              this.correctRate = parseFloat(response.right_rate.toFixed(2));
            } else {
              this.$Message.error(response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      }
    },
    connectUs() {
      this.showComt = true;
      // this.$router.push({
      //   name: "connectUs",
      //   params: {
      //     menu: this.currentPoint.menu,
      //     point: this.point,
      //     last: this.currentPoint.last,
      //     flag: this.currentPoint.flag
      //   }
      // });
    },
    cancel() {
      this.showComt = false;
    }
  }
};
</script>